<?php

namespace app\common\service;


use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use app\common\helper\FormatHelper;
use plugins\ALiYun\VoiceClass;
use think\Db;

/**
 * 生成语音合成服务
 *
 * Class ActivityService
 * @package app\common\service
 */
class VoiceService
{

    /**
     * 文本生成语音文件服务
     *
     * @param string $text 文本
     * @param int $speech_rate 语速
     * @param int $for_num 播放次数
     * @return array
     */
    public static function createVoice($text, $speech_rate = 1.5, $for_num = 1)
    {
        if (empty($text)) {
            return FormatHelper::fReturn('文本信息不能为空！', '', FormatHelper::ERROR);
        }
        //语速
        switch ($speech_rate) {
            case $speech_rate == 0.5:
                $speech_rate = 50;
                break;
            case $speech_rate == 1:
                $speech_rate = 100;
                break;
            case $speech_rate == 1.5:
                $speech_rate = 150;
                break;
            case $speech_rate == 2:
                $speech_rate = 200;
                break;
            default:
                $speech_rate = 0;
                break;
        }

        $content = '';
        for ($i = 1; $i <= $for_num; $i++) {
            $content .= $text . '    ';
        }
        $config = config('ali_voice');
        $app_key = $config['app_key'];//语音合成key
        //$token = $config['token'];//语音合成token
        $token = self::AlibabaClouds();

        $textUrlEncode = urlencode($content);
        $textUrlEncode = preg_replace('/\+/', '%20', $textUrlEncode);
        $textUrlEncode = preg_replace('/\*/', '%2A', $textUrlEncode);
        $textUrlEncode = preg_replace('/%7E/', '~', $textUrlEncode);
        $audioSaveFile = "syAudio.wav";
        $format = "wav";
        $sampleRate = 16000;
        $voice_class = new VoiceClass();
        $result = $voice_class->processGETRequest($app_key, $token, $textUrlEncode, $audioSaveFile, $format, $sampleRate, $speech_rate);
        //$voice_class->processPOSTRequest($appkey, $token, $text, $audioSaveFile, $format, $sampleRate);
        //var_dump($result);exit();
        return FormatHelper::fReturn('生成文件成功', $result, FormatHelper::SUCCESS);

    }

    /**
     * 第一步：设置一个全局客户端
     * 使用阿里云RAM账号的AccessKey ID和AccessKey Secret进行鉴权。
     */
    public static function AlibabaClouds () {

        $config = config('alibaba');
        AlibabaCloud::accessKeyClient(
            $config['accessKeyId'],
            $config['accessKeySecret'])
            ->regionId("cn-shanghai")
            ->asDefaultClient();
        try {
            $response = AlibabaCloud::nlsCloudMeta()->v20180518()->createToken()->request();
            //print $response . "\n";
            $token = $response["Token"];
            if ($token != NULL) {
                //print "Token 获取成功：\n";
                //print_r($token);
                return $token['Id'];
            }
            else {
                print "token 获取失败\n";
            }
        } catch (ClientException $exception) {
            // 获取错误消息
            print_r($exception->getErrorMessage());
        } catch (ServerException $exception) {
            // 获取错误消息
            print_r($exception->getErrorMessage());
        }
    }


    /**
     * 合成语音信息
     *
     * @param $store_id   [门店ID]
     * @param $text         [文本内容]
     * @param $voice_url    [语音地址]
     * @param $voice_type   [语音类型]  1下商品 2退商品 3下项目 4退项目 5上钟 6下钟 7 预约 8 催钟
     * @param $type     [类型] 1商品 2项目 3 技师消息
     */
    public static function saveVoiceMsg($store_id,$text,$voice_url,$voice_type,$type,$engineerId = ''){

        $data = [
            'store_id'=>$store_id,
            'engineer_id'=>$engineerId,
            'voice_type'=>$voice_type,//语音类型 1下商品 2退商品 3下项目 4退项目 5上钟 6下钟
            'content'=>$text,
            'type'=>$type,//类型 1商品 2项目
            'voice_url'=>$voice_url,
            'create_time'=>time(),
            'is_create_voice'=>1,
        ];

        Db::name('qt_send_voice_msg')->insert($data);

    }


    /**
     * 更新合成语音信息
     *
     * @param $id               消息ID
     * @param $voice_url        音频地址
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public static function updateVoiceMsg($id,$voice_url) {

        Db::name('qt_send_voice_msg')->where('id',$id)->update(['voice_url'=>$voice_url,'is_create_voice'=>1]);

    }


}